//
//  SuiTangLianXiVC.m
//  ZhiBoYuan
//
//  Created by apple on 2018/4/17.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "SuiTangLianXiVC.h"

#import "ExercisesModel.h"
#import "ExercisesItem.h"

#import "PaperViewController.h"
#import "ToolHeader.h"

#import "PaperViewControllerBuild.h"

static NSString *ident = @"SuiTangLiangXiCell";


@interface SuiTangLianXiVC ()
<
UITableViewDataSource,
UITableViewDelegate
>

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger pageIndex;


@property (nonatomic,strong)UIView *headView;
@property (nonatomic, assign)BOOL canScroll;
@end

@implementation SuiTangLianXiVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self setupConfigureView];
    [self downloadCourseLianXiDatas];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptMsg:) name:TABLETOP object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptMsg:) name:TABLELEAVETOP object:nil];


    
}
- (void)acceptMsg:(NSNotification *)notification
{
    NSString *notificationName = notification.name;
    if ([notificationName isEqualToString:TABLETOP])
    {
        NSDictionary *userInfo = notification.userInfo;
        NSString *can = userInfo[NotificationCanScroll];
        if ([can isEqualToString:@"1"])
        {
            self.canScroll = YES;
            self.tableView.showsVerticalScrollIndicator = YES;
        }
        
    }
    else if ([notificationName isEqualToString:TABLELEAVETOP])
    {
        self.canScroll = NO;
        self.tableView.showsVerticalScrollIndicator = NO;
        self.tableView.contentOffset = CGPointZero;
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (!self.canScroll)
    {
        [scrollView setContentOffset:CGPointZero];
    }
    CGFloat offSetY = scrollView.contentOffset.y;
    
    if (offSetY < 0)
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:TABLELEAVETOP object:nil userInfo:@{NotificationCanScroll: @"1"}];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)downloadCourseLianXiDatas{
    SGParameter *parameter  = [[SGParameter alloc] init];
    parameter.body = @{
//                      @"page":@"1",
                       @"course_id":self.course_id
                       };
    [SGHttpTool POST:Host_Append(CourseExercises) parameter:parameter sucess:^(id responseObject) {
        //成功回调
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
        NSString *resultStr =[[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"%@",resultStr);
        SGReceive *receive = [SGReceive receiveWithResponseObject:responseObject dataWord:@"chapter_list"dataClass:[ExercisesModel class]];
        [self.dataArray addObjectsFromArray:receive.data];
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
    
    
}

- (void)setupConfigureView{
    [self.view addSubview:self.tableView];
    
    self.tableView.sd_layout
    .topSpaceToView(self.view, 0)
    .leftSpaceToView(self.view, 0)
    .rightSpaceToView(self.view, 0)
    .bottomSpaceToView(self.view, 0);
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString * identy = @"head";
    
    UITableViewHeaderFooterView * hf = [tableView dequeueReusableHeaderFooterViewWithIdentifier:identy];
    
    if (!hf) {
        
        hf = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:identy];
        
        UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0,0, self.view.frame.size.width,40)];
        
        view.backgroundColor = hui1Color;
//        NSArray *arr = @[@"第一节 第一时 课程怎么学",
//                         @"第二节 第一时 课程怎么学广告专区",
//                         @"第三节 第一时 课程怎么学最近直播",
//                         @"第一节 第一时 课程怎么学热门直播"];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, self.view.frame.size.width-80, 40)];
        ExercisesModel *model = self.dataArray[section];
        label.text = [NSString stringWithFormat:@"%@:%@",model.order_name,model.name];
        
        [view addSubview:label];
        
        //        UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
        //
        //        button.tag = section + 100;
        //
        //        button.frame = CGRectMake(ScreenWidth-60, 0, 50, 40);
        //        [button setTitle:@"更多" forState:(UIControlStateNormal)];
        //
        //        BTN_MSG_FUNC(button, sender:);
        //
        //        [button setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
        //
        //        [view addSubview:button];
        
        
        [hf addSubview:view];
        
    }
    
    return hf;
    
    
}

#pragma mark -- UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    ExercisesModel *model = self.dataArray[section];

    return model.child.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ident forIndexPath:indexPath];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    ExercisesModel *model = self.dataArray[indexPath.section];
    ExercisesItem *item = model.child[indexPath.row];

    cell.textLabel.text = [NSString stringWithFormat:@"%@:%@(共%ld题)",item.order_name,item.name,(long)item.question_count];
    
    return cell;
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return SNRealValue(50);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    ExercisesModel *model = self.dataArray[indexPath.section];
    if (model.had_buy == 0 && !Teacher) {
        [MBProgressHUD showTextOnly:self.view message:@"请先加入学习" delay:1.5];
        return;
    }
    ExercisesItem *item = model.child[indexPath.row];
    
    PaperViewController * paper;
    
    if (item.had_do == 1) {//做过
        paper = [PaperViewControllerBuild createIntelligentAllAnalyViewControllerWithData:@{}];
        paper.ID = item.ID;
        paper.answerType = @"chapter_id";
        paper.url = ChapterQuestionList;
        
    }else if (item.had_do == 0){//没做过
        paper = [PaperViewControllerBuild createIntelligentViewController];
        paper.ID = item.ID;
        paper.answerType = @"chapter_id";
        paper.url = ChapterQuestionList;
//        paper.url = @"g=Client&m=Question&a=chapterQuestionList";

    }
    
//    PaperViewController * paper = [PaperViewControllerBuild createIntelligentViewController];
//    ExercisesModel *model = self.dataArray[indexPath.section];
//    ExercisesItem *item = model.child[indexPath.row];
//    
//    paper.chapter_id = item.ID;
    paper.hidesBottomBarWhenPushed =YES;
    [ZYCurrentViewController().navigationController pushViewController:paper animated:YES];
}

#pragma mark - 去做题
- (void)startToAnswer:(NSString *)video_id{
    if (Teacher) {
        return;
    }
    __block ExercisesItem *currentItem;
    
    [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        ExercisesModel *model = obj;
        NSArray *child = model.child;
        
        [child enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            ExercisesItem *item = child[idx];
            if ([item.ID isEqualToString:video_id]) {
                currentItem = item;
                *stop = YES;
            }
        }];
        if (currentItem) {
             *stop = YES;
        }
        
    }];
    
    PaperViewController * paper;
    
    if (currentItem.had_do == 1) {//做过
        paper = [PaperViewControllerBuild createIntelligentAllAnalyViewControllerWithData:@{}];
        paper.ID = currentItem.ID;
        paper.answerType = @"chapter_id";
        paper.url = ChapterQuestionList;
        
        
    }else if (currentItem.had_do == 0){//没做过
        paper = [PaperViewControllerBuild createIntelligentViewController];
        paper.ID = currentItem.ID;
        paper.answerType = @"chapter_id";
        paper.url = ChapterQuestionList;
        
    }
    
    //    PaperViewController * paper = [PaperViewControllerBuild createIntelligentViewController];
    //    ExercisesModel *model = self.dataArray[indexPath.section];
    //    ExercisesItem *item = model.child[indexPath.row];
    //
    //    paper.chapter_id = item.ID;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        paper.hidesBottomBarWhenPushed =YES;
        [ZYCurrentViewController().navigationController pushViewController:paper animated:YES];
    });

}

#pragma mark - 购买完成重置课程状态

- (void)setBuyState:(NSInteger)buyState{
    _buyState = buyState;
    
    [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        ExercisesModel *model = obj;
        model.had_buy = buyState;
    }];
}

#pragma makr -- property
- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (UITableView *)tableView {
    if (!_tableView) {
        UITableView *  tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
        //        tableView.backgroundColor = [UIColor greenColor];
        tableView.delegate        = self;
        tableView.dataSource      = self;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        tableView.estimatedRowHeight = 44.0f;//推测高度，必须有，可以随便写多少
        
        tableView.rowHeight = UITableViewAutomaticDimension;//iOS8之后默认就是这个值，可以省略
        
        //        self.extendedLayoutIncludesOpaqueBars = YES;
        
        //        if (@available(iOS 11.0, *)) {
        //            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        //        } else {
        //            self.automaticallyAdjustsScrollViewInsets = NO;
        //        }
        //        tableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
        //        tableView.scrollIndicatorInsets = _tableView.contentInset;
        
        //         [tableView registerNib:[UINib nibWithNibName:identC bundle:nil] forCellReuseIdentifier:identC];
        //        [tableView registerNib:[UINib nibWithNibName:ident bundle:nil] forCellReuseIdentifier:identB];
        
//        [tableView registerNib:[UINib nibWithNibName:ident bundle:nil] forCellReuseIdentifier:ident];
        
        [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:ident];
        
        [tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
        //        __weak __typeof(&*self)weakSelf = self;
        
        // 下拉刷新
        //        tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //
        //            weakSelf.pageIndex = 1;
        //
        //            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //                [weakSelf.tableView.mj_header endRefreshing];
        //            });
        //        }];
        //
        //        // 上拉加载
        //        tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        //
        //            if ( weakSelf.pageIndex < -1 ) {  weakSelf.pageIndex = 1;  }
        //
        //            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //                [weakSelf.tableView.mj_footer endRefreshing];
        //            });
        //        }];
        _tableView = tableView;
        
    }
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}



@end
